// Copyright 2007 Google, Inc. All Rights Reserved.

package com.google.jessewilson.codesearch.intellij.dfs;

import com.google.jessewilson.codesearch.api.CodeFile;
import com.google.jessewilson.codesearch.io.Path;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileSystem;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.jetbrains.annotations.NotNull;

/**
 * @author jessewilson
 */
public class DownloadedDirectory extends VirtualFile {

  private final DownloadedFileSystem fileSystem;
  private final Path path;
  private final List<DownloadedFile> children = new ArrayList<DownloadedFile>();

  DownloadedDirectory(DownloadedFileSystem fileSystem, Path path) {
    this.fileSystem = fileSystem;
    this.path = path;
  }

  void addChild(DownloadedFile child) {
    this.children.add(child);
  }

  /**
   * Returns the child for the specified {@link com.google.jessewilson.codesearch.api.CodeFile}, or {@code null} if
   * no such child exists.
   */
  public DownloadedFile getChild(CodeFile codeFile) {
    for(DownloadedFile child : children) {
      if(child.getCodeFile().equals(codeFile)) {
        return child;
      }
    }
    return null;
  }

  public String getName() {
    return path.getFileName();
  }

  public VirtualFileSystem getFileSystem() {
    return fileSystem;
  }

  public String getPath() {
    return path.toString();
  }

  public boolean isWritable() {
    return false;
  }

  public boolean isDirectory() {
    return true;
  }

  public boolean isValid() {
    return true;
  }

  public VirtualFile getParent() {
    return null;
  }

  public VirtualFile[] getChildren() {
    return children.toArray(new VirtualFile[children.size()]);
  }

  public OutputStream getOutputStream(Object requestor,
      long newModificationStamp, long newTimeStamp) throws IOException {
    throw new UnsupportedOperationException();
  }

  public byte[] contentsToByteArray() throws IOException {
    throw new UnsupportedOperationException();
  }

  public long getTimeStamp() {
    return 0;
  }

  public long getLength() {
    return 0;
  }

  public void refresh(boolean asynchronous, boolean recursive,
      Runnable postRunnable) {
    // do nothing
  }

  public InputStream getInputStream() throws IOException {
    throw new UnsupportedOperationException();
  }

  @NotNull public String getUrl() {
    return getPath();
  }
}
